package umputun.jutw.storage;

/*
 Copyright 2009 Umputun

 This file is part of JUTW.

 JUTW is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 JUTW is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with JUTW.  If not, see http://www.gnu.org/licenses/.
*/

import umputun.jutw.utils.logging.ULogger;

import java.io.*;
import java.math.BigInteger;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class FileStorage implements IDataStorage{

	public FileStorage(String root_location) {
		this.root_location = root_location;
		log.fine("storage created for location="+root_location);
	}


	@Override
	public void setUserLastTwiID(String user, BigInteger id) throws DataStorageException {
		last_ids.put(user, id);

		try {
			FileWriter wrt = new FileWriter(new File(getIdLocation(user)));
			wrt.write(String.valueOf(id) + "\n");
			wrt.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public BigInteger getUserLastTwiID(String user) {
		if (!last_ids.containsKey(user)) {
			File fh = new File(getIdLocation(user));
			if (fh.exists()) {
				try {
					BufferedReader rdr = new BufferedReader(new FileReader(fh));
					String line = rdr.readLine();
					rdr.close();
					return new BigInteger(line);
				}
				catch (Throwable ex) {
					return new BigInteger("0");
				}
			}
			return new BigInteger("0");
		}
		return last_ids.get(user);
	}


	private String getIdLocation(String user) {
		if (root_location == null || root_location.equals(""))
			return (user + ".id");
		return (root_location + File.separatorChar + user + ".id");
	}

	@Override
	public void setUserLastRssID(String user, long id) throws DataStorageException {
		// TODO Auto-generated method stub
	}


	@Override
	public long getUserLastRssID(String user) {
		// TODO Auto-generated method stub
		return 0;
	}

	private final Map<String, BigInteger> last_ids = new ConcurrentHashMap<String, BigInteger>();
	private final String root_location;
	private static final ULogger log = ULogger.getLogger();

}
